<template>
  <div class="emoticon_main">
    <div class="emoticon_scroll" ref="emoticonScroll">
      <div class="emoticon_item" v-for="(img, index) in imgs" :key="img.id">
        <el-image
          :src="img.url"
          class="emoticon_img"
          :lazy="index > 28"
          @click="handleClick(img, index)"
        >
          <div slot="placeholder" v-if="index > 28" class="image-slot">{{$t('webchat.loading')}}</div>
        </el-image>
        <div class="emoticon_img_del" v-show="deleteshow">
          <el-checkbox v-model="checkList[index]" :true-label="img._id" :false-label="falseLabel"></el-checkbox>
        </div>
      </div>
    </div>
    <div class="handle">
      <el-button
        class="btn"
        v-show="!deleteshow && addPermissions"
        icon="el-icon-plus"
        id="emoticon_upload"
        @click="overMax"
      ></el-button>
      <el-button class="btn" v-show="!deleteshow" icon="el-icon-minus" @click="openDelete"></el-button>
      <el-button
        class="textbtn"
        :disabled="judgmentDelete"
        type="text"
        v-show="deleteshow"
        @click="deleteImg(checkList)"
      >{{$t('webchat.deleteSelected')}}</el-button>
      <el-button
        class="textbtn"
        type="text"
        v-show="deleteshow"
        @click="reset2"
      >{{$t('public.cancel')}}</el-button>
    </div>
  </div>
</template>
<script type="text/javascript">
const delay = (function () {
  let timer = 0
  return function (callback, ms) {
    clearTimeout(timer)
    timer = setTimeout(callback, ms)
  }
})()
import { isHasFunc } from '@/utils/m7Utils.js'
export default {
  name: 'Emoticon',
  data() {
    return {
      imgs: [], // 图片列表
      imgscopy: [], // 图片列表备份
      toshow: false, // 组件显示
      deleteshow: false, // 删除功能开启关闭
      checkList: [], // 删除的id数组
      falseLabel: 'unselected', // 未选中的值，elementui需要使用
      addPermissions: true, // 添加权限
      judgmentDelete:true,
      pages: {
        // 查询条件
        limit: 100,
        page: 1,
      },
    }
  },
  methods: {
    handleClick(val, i) {
      if (this.deleteshow) {
        //点击图片时候选中或取消选中
        if (this.checkList[i] === 'unselected' || !this.checkList[i]) {
          this.$set(this.checkList, i, val._id)
        } else {
          this.$set(this.checkList, i, 'unselected')
        }
      } else {
        let imgsrc = this.formatSrc(val.url)
        this.$emit('sendimg', {}, 'image', imgsrc) //触发发送图片事件
      }
    },
    mainShow() {
      this.toshow = true
    },
    // 添加表情包
    addEmoticon(img) {
      let data = {
        docs: [{ type: 'image', url: img.src }],
      }
      this.$store.dispatch('addAgentMeme', data).then((res) => {
        delay(this.getEmoticon, 500)
      })
    },
    // 查找表情包
    getEmoticon(callback) {
      this.$store.dispatch('getAgentMeme', this.pages).then((res) => {
        for (let i = 0; i < res.data.docs.length; i++) {
          const element = res.data.docs[i]
          element.url = this.formatSrc(element.url)
        }
        this.imgs = res.data.docs
        if (document.querySelector('.handle .moxie-shim')){
          if (this.imgs.length >= 99) {
            document.querySelector('.handle .moxie-shim').style.display = 'none'
          } else {
            if (!this.deleteshow) {
              document.querySelector('.handle .moxie-shim').style.display = 'block'
            }
          }
        }
        this.$store.commit('webchat/UPDATE_EMOTICONNUMBER', this.imgs.length)
        callback && callback()
      })
    },
    // 删除表情包
    deleteImg(array) {
      let ids = []
      for (let i = 0; i < array.length; i++) {
        const element = array[i]
        if(element !== 'unselected'){
          ids.push(element)
        }
      }
      let idsobj = { ids }
      this.$store.dispatch('deleteAgentMeme', idsobj).then((res) => {
        this.getEmoticon(() => {
          this.checkList = []
        })
      })
    },
    openDelete() {
      this.deleteshow = true
      document.querySelector('.handle .moxie-shim').style.display = 'none'
    },
    scroll() {
      this.$refs.emoticonScroll.scrollBy(1, 1)
      this.$refs.emoticonScroll.scrollBy(-1, -1)
    },
    // judgmentDelete() {
    //   let array = this.checkList
    //   for (let i = 0; i < array.length; i++) {
    //     const element = array[i]
    //     if (element !== 'unselected') return false
    //   }
    //   return true
    // },
    overMax() {
      if (this.imgs.length >= 99) {
        this.$message.error(this.$t('webchat.overMax'))
      }
    },
    // 格式化图片资源
    formatSrc(val) {
      let gifLog = '?imageView2/1/w/44/format/jpg' // gif 转 jpg 节省资源，不会动
      let otherLog = '?imageView2/2/w/44' // 压缩png等其他图片
      let Log = otherLog
      if (val.indexOf('.gif')) Log = gifLog
      return val.split('?').length === 2 ? val.split('?')[0] : val + Log // 如果有，就去掉，如果没有，就加上
    },
    reset() {
      this.$refs.emoticonScroll.scroll(0, 0)
      this.deleteshow = false
      this.checkList = new Array(this.imgs.length).fill('unselected')
    },
    reset2() {
      this.deleteshow = false
      this.checkList = new Array(this.imgs.length).fill('unselected')
      document.querySelector('.handle .moxie-shim').style.display = 'block'
      if (this.imgs.length > 98)
        document.querySelector('.handle .moxie-shim').style.display = 'none'
    },
  },
  beforeMount() {
    this.getEmoticon(()=>{this.checkList = new Array(this.imgs.length).fill('unselected')})
  },
  mounted() {
    this.$emit('initialization')
    if (isHasFunc('func_not_allow_add_agent_meme', this.$store.state.session.user)) {
      this.addPermissions = false
      this.$nextTick(()=>{
       let dom = document.querySelector('.handle .moxie-shim')
       if(dom) dom.style.display = 'none'
      })
    }
  },
  watch: {
    checkList: {
      handler(n, o) {
        console.log(123123123)
        let array = this.checkList
        this.judgmentDelete = true
        for (let i = 0; i < array.length; i++) {
          const element = array[i]
          if (element !== 'unselected') {
            this.judgmentDelete = false
            break
          }
        }
      },
      deep: true
    },
  },
}
</script>
<style lang="stylus" scoped>
/deep/.el-checkbox__inner
  border-radius 50%
.btn
  height 20px
  width 20px
  padding 0
.textbtn
  padding 0
.emoticon_main
  display flex
  flex-wrap wrap
  height 208px
  overflow hidden
  position relative
  padding 0 8px
  .emoticon_scroll
    text-align justify
    height 183px
    overflow auto
    min-width 100px
    .emoticon_item
      height 44px
      width 44px
      position relative
      display inline-block
      margin 8px
      img
        height 44px
        width 44px
    .emoticon_item:nth-child(8n)
      margin-right 2px
  .handle
    width 100%
    height 25px
    line-height 25px
    text-align right
.emoticon_img
  cursor pointer
  position relative
  display flex
  justify-content center
  align-items center
.emoticon_img_del
  position absolute
  bottom 0
  right 0
.deleteshow
  .moxie-shim-html5
    display none !important
.emoticon_item
  .emoticon_img
    position relative
    top 50%
    transform translateY(-50%)
</style>
